import "dart:io";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/pre_check_in/api.dart";
import "package:ct_pa_majordomo/pages/commonApi.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/bottom_sheet/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:flutter/material.dart";
import "package:flutter/cupertino.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:image_picker/image_picker.dart";
import "package:dio/dio.dart";
import "package:permission_handler/permission_handler.dart";

class PreCheckInEdit extends StatefulWidget {
  final int? registerId;

  const PreCheckInEdit({super.key, this.registerId});

  @override
  State<PreCheckInEdit> createState() => _PreCheckInEditState();
}

class _PreCheckInEditState extends State<PreCheckInEdit> {
  // 表单控制器
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _idCardController = TextEditingController();
  final TextEditingController _contactsController = TextEditingController();
  
  // 同住人列表
  List<Map<String, dynamic>> _cotenantList = [];
  
  // 承租人信息
  Map<String, dynamic> _mainRenter = {
    "name": "",
    "idCardNumber": "",
    "contacts": "",
    "picUrl": "", // 人脸图片
    "renterType": "", // 房客类型：1为省内，2为省外
    "mainFlag": "1" // 1:承租人 2:同住人
  };

  // 图片选择器
  late ImagePicker _imagePicker;
  
  // 房间相关
  int? _selectedRoomId;
  String _selectedRoomName = "";
  String _selectedBuildingName = "";
  List<Map<String, dynamic>> _emptyRoomList = [];
  
  // 是否为编辑模式
  bool get isEdit => widget.registerId != null;
  
  // 获取预登记详情
  Future<void> _getPreCheckInDetail() async {
    try {
      EasyLoading.show();
      Map resData = await preCheckInApi.getPreCheckInDetail(widget.registerId);
      EasyLoading.dismiss();
      
      List renterList = resData["data"]["renterList"] ?? [];
      
      // 分离承租人和同住人
      _cotenantList = []; // 清空同住人列表，避免重复添加
      for (var renter in renterList) {
        if (renter["mainFlag"] == "1") {
          // 承租人
          setState(() {
            _mainRenter = Map<String, dynamic>.from(renter);
            _nameController.text = _mainRenter["name"] ?? "";
            _idCardController.text = _mainRenter["idCardNumber"] ?? "";
            _contactsController.text = _mainRenter["contacts"] ?? "";
            // 确保picUrl和其他字段也被正确设置
            if (_mainRenter["picUrl"] == null) {
              _mainRenter["picUrl"] = "";
            }
            if (_mainRenter["renterType"] == null) {
              _mainRenter["renterType"] = "";
            }
          });
        } else {
          // 同住人
          Map<String, dynamic> cotenant = Map<String, dynamic>.from(renter);
          // 确保所有必要字段都存在
          cotenant["mainFlag"] = cotenant["mainFlag"] ?? "2";
          cotenant["picUrl"] = cotenant["picUrl"] ?? "";
          cotenant["idCardNumber"] = cotenant["idCardNumber"] ?? "";
          cotenant["name"] = cotenant["name"] ?? "";
          cotenant["contacts"] = cotenant["contacts"] ?? "";
          cotenant["renterType"] = cotenant["renterType"] ?? "";
          
          setState(() {
            _cotenantList.add(cotenant);
          });
        }
      }
      
      // 设置房间信息
      if (resData["data"]["roomId"] != null) {
        _selectedRoomId = resData["data"]["roomId"];
        await _getRoomInfo(_selectedRoomId!);
      }
      
      print("预登记详情加载完成: 承租人=${_mainRenter['name']}, 同住人数量=${_cotenantList.length}");
    } catch (error) {
      EasyLoading.dismiss();
      EasyLoading.showError("获取预登记详情失败");
      print("获取预登记详情错误: $error");
    }
  }
  
  // 获取房间信息
  Future<void> _getRoomInfo(int roomId) async {
    try {
      Map resData = await apartmentApi.getRoomInfo(roomId);
      setState(() {
        _selectedRoomName = resData["data"]["name"] ?? "";
        _selectedBuildingName = resData["data"]["buildingName"] ?? "";
      });
    } catch (e) {
      print("获取房间信息失败: $e");
    }
  }
  
  // 获取空闲房间列表
  Future<void> _getEmptyRoomList() async {
    try {
      EasyLoading.show();
      Map resData = await apartmentApi.getEmptyRoomList({
        "pageNum": 1,
        "pageSize": 999,
      });
      EasyLoading.dismiss();
      setState(() {
        _emptyRoomList = List<Map<String, dynamic>>.from(resData["rows"] ?? []);
      });
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError("获取空闲房间列表失败");
      print("获取空闲房间列表错误: $e");
    }
  }
  
  // 显示房间选择底部弹窗
  void _showRoomSelectionBottomSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (BuildContext context) {
        return Container(
          constraints: BoxConstraints(
            maxHeight: MediaQuery.of(context).size.height * 0.7,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              // 标题栏
              Container(
                padding: const EdgeInsets.all(16),
                decoration: const BoxDecoration(
                  border: Border(
                    bottom: BorderSide(color: ThemeVars.colorDivider),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      "选择房间",
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    IconButton(
                      onPressed: () => Navigator.pop(context),
                      icon: const Icon(Icons.close),
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                    ),
                  ],
                ),
              ),
              // 房间列表
              Expanded(
                child: _emptyRoomList.isEmpty
                    ? const Center(
                        child: Text("暂无空闲房间"),
                      )
                    : ListView.separated(
                        padding: const EdgeInsets.symmetric(vertical: 8),
                        itemCount: _emptyRoomList.length,
                        separatorBuilder: (context, index) => const Divider(
                          height: 1,
                          color: ThemeVars.colorDivider,
                        ),
                        itemBuilder: (context, index) {
                          Map<String, dynamic> room = _emptyRoomList[index];
                          return ListTile(
                            contentPadding: const EdgeInsets.symmetric(
                              horizontal: 16,
                              vertical: 4,
                            ),
                            title: Text(
                              "${room["buildingName"]} ${room["name"]}",
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                            trailing: _selectedRoomId == room["roomId"]
                                ? const Icon(
                                    Icons.check_circle,
                                    color: ThemeVars.colorPrimary,
                                  )
                                : null,
                            onTap: () {
                              setState(() {
                                _selectedRoomId = room["roomId"];
                                _selectedRoomName = room["name"] ?? "";
                                _selectedBuildingName = room["buildingName"] ?? "";
                              });
                              Navigator.pop(context);
                            },
                          );
                        },
                      ),
              ),
            ],
          ),
        );
      },
    );
  }
  
  // 保存预登记信息
  Future<void> _savePreCheckIn() async {
    // 检查承租人必填项
    if (_mainRenter["renterType"].toString().isEmpty) {
      EasyLoading.showToast("请选择承租人房客类型");
      return;
    }
    if (_nameController.text.isEmpty) {
      EasyLoading.showToast("请输入承租人姓名");
      return;
    }
    if (_contactsController.text.isEmpty) {
      EasyLoading.showToast("请输入承租人联系方式");
      return;
    }
    if (_selectedRoomId == null) {
      EasyLoading.showToast("请选择入住房间");
      return;
    }
    
    // 校验同住人信息
    for (int i = 0; i < _cotenantList.length; i++) {
      Map<String, dynamic> cotenant = _cotenantList[i];
      if (cotenant["renterType"].toString().isEmpty) {
        EasyLoading.showToast("请选择同住人${i + 1}房客类型");
        return;
      }
      if (cotenant["name"].toString().isEmpty) {
        EasyLoading.showToast("请输入同住人${i + 1}姓名");
        return;
      }
      if (cotenant["contacts"].toString().isEmpty) {
        EasyLoading.showToast("请输入同住人${i + 1}联系方式");
        return;
      }
    }
    
    // 构建承租人信息
    _mainRenter["name"] = _nameController.text;
    _mainRenter["idCardNumber"] = _idCardController.text;
    _mainRenter["contacts"] = _contactsController.text;
    
    // 构建完整的renterList
    List<Map<String, dynamic>> renterList = [_mainRenter, ..._cotenantList];
    
    // 构建请求参数
    Map<String, dynamic> params = {
      "roomId": _selectedRoomId,
      "renterList": renterList
    };
    
    // 如果是编辑模式，则添加registerId
    if (isEdit) {
      params["registerId"] = widget.registerId;
    }
    
    try {
      EasyLoading.show();
      if (isEdit) {
        await preCheckInApi.updatePreCheckIn(params);
        EasyLoading.showSuccess("修改成功");
      } else {
        await preCheckInApi.addPreCheckIn(params);
        EasyLoading.showSuccess("添加成功");
      }
      
      // 返回并刷新列表
      if (mounted) {
        Navigator.pop(context, true);
      }
    } catch (error) {
      EasyLoading.dismiss();
      EasyLoading.showError("保存失败: ${error.toString()}");
      print("保存预登记信息错误: $error");
    }
  }

  // 显示选择图片来源的底部弹窗
  void _showImageSourceOptions(bool isMainRenter, [int? cotenantIndex]) {
    bool isPickerActive = false;
    
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
        title: const Text('选择图片来源'),
        actions: <CupertinoActionSheetAction>[
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              Future.microtask(() {
                _takePhoto(isMainRenter, cotenantIndex).then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("拍照操作错误: $e");
                });
              });
            },
            child: const Text('拍照'),
          ),
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              Future.microtask(() {
                _pickImage(isMainRenter, cotenantIndex).then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("选择图片操作错误: $e");
                });
              });
            },
            child: const Text('从相册选择'),
          ),
        ],
        cancelButton: CupertinoActionSheetAction(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('取消'),
        ),
      ),
    );
  }

  // 拍照获取图片
  Future<void> _takePhoto(bool isMainRenter, [int? cotenantIndex]) async {
    try {
      var status = await Permission.camera.status;
      if (status.isDenied) {
        await Permission.camera.request();
      } else if (status.isGranted) {
        final picker = ImagePicker();
        final pickedImage = await picker.pickImage(
          source: ImageSource.camera,
          preferredCameraDevice: CameraDevice.front,
          imageQuality: 80,
        );

        if (pickedImage != null && mounted) {
          await _uploadImage(pickedImage, isMainRenter, cotenantIndex);
        }
      }
    } catch (e) {
      print("拍照错误: ${e.toString()}");
      EasyLoading.showError("拍照失败：${e.toString()}");
    }
  }

  // 从相册选择图片
  Future<void> _pickImage(bool isMainRenter, [int? cotenantIndex]) async {
    try {
      final picker = ImagePicker();
      final pickedImage = await picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 80,
      );
      
      if (pickedImage != null && mounted) {
        await _uploadImage(pickedImage, isMainRenter, cotenantIndex);
      }
    } catch (e) {
      print("选择图片错误: ${e.toString()}");
      EasyLoading.showError("选择图片失败：${e.toString()}");
    }
  }

  // 上传图片
  Future<void> _uploadImage(XFile imageFile, bool isMainRenter, [int? cotenantIndex]) async {
    try {
      EasyLoading.show(status: "上传中...");
      final file = File(imageFile.path);
      
      // 检查文件大小是否超过5M
      final fileSize = await file.length();
      final sizeInMB = fileSize / (1024 * 1024);
      if (sizeInMB > 5) {
        EasyLoading.dismiss();
        EasyLoading.showToast("请上传小于5M的图片");
        return;
      }

      FormData formData = FormData();
      formData.files.add(MapEntry(
        "file",
        await MultipartFile.fromFile(file.path, filename: "face_${DateTime.now().millisecondsSinceEpoch}.jpg")
      ));

      Map res = await commonApi.upload(formData);
      EasyLoading.dismiss();

      if (res["code"].toString() != "200") {
        EasyLoading.showError("上传失败：${res["msg"] ?? "未知错误"}");
        return;
      }

      // 更新对应的图片URL
      setState(() {
        if (isMainRenter) {
          _mainRenter["picUrl"] = res["data"]["url"];
        } else if (cotenantIndex != null) {
          _cotenantList[cotenantIndex]["picUrl"] = res["data"]["url"];
        }
      });
      EasyLoading.showSuccess("上传成功");
    } catch (e) {
      EasyLoading.dismiss();
      print("上传图片错误: ${e.toString()}");
      EasyLoading.showError("上传失败：${e.toString()}");
    }
  }

  // 渲染人脸图片区域
  Widget _renderFace(String? picUrl) {
    return Container(
      width: 120,
      height: 120,
      decoration: BoxDecoration(
        color: ThemeVars.colorBackground,
        borderRadius: BorderRadius.circular(4),
      ),
      child: picUrl != null && picUrl.isNotEmpty
          ? Stack(
              fit: StackFit.expand,
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: Image.network(
                    picUrl,
                    fit: BoxFit.cover,
                    loadingBuilder: (context, child, loadingProgress) {
                      if (loadingProgress == null) return child;
                      return Center(
                        child: CircularProgressIndicator(
                          value: loadingProgress.expectedTotalBytes != null
                              ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
                              : null,
                        ),
                      );
                    },
                    errorBuilder: (context, error, stackTrace) {
                      return const Center(
                        child: Icon(Icons.error, color: Colors.red),
                      );
                    },
                  ),
                ),
                Positioned(
                  right: 0,
                  top: 0,
                  child: Container(
                    padding: const EdgeInsets.all(2),
                    decoration: const BoxDecoration(
                      color: Colors.black54,
                      borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(4),
                        topRight: Radius.circular(4),
                      ),
                    ),
                    child: const Icon(
                      Icons.check_circle,
                      color: Colors.green,
                      size: 16,
                    ),
                  ),
                ),
              ],
            )
          : const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.add_a_photo, size: 36, color: ThemeVars.colorTextTer),
                  SizedBox(height: 8),
                  Text("添加人脸", style: TextStyle(color: ThemeVars.colorTextTer, fontSize: 12)),
                ],
              ),
            ),
    );
  }
  
  // 显示房客类型选择底部弹窗
  void _showRenterTypeSelectionBottomSheet(bool isMainRenter, [int? cotenantIndex]) {
    // 房客类型选项
    List<Map<String, String>> renterTypeOptions = [
      {"value": "1", "label": "省内"},
      {"value": "2", "label": "省外"},
    ];
    
    // 获取当前选中的索引
    String currentValue = isMainRenter 
        ? _mainRenter["renterType"] 
        : (cotenantIndex != null ? _cotenantList[cotenantIndex]["renterType"] : "");
    
    int selectedIndex = renterTypeOptions.indexWhere((item) => item["value"] == currentValue);
    if (selectedIndex == -1) selectedIndex = 0;
    
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 300,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
          ),
          child: Column(
            children: [
              // 标题栏
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                decoration: const BoxDecoration(
                  border: Border(
                    bottom: BorderSide(color: ThemeVars.colorDivider),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    CupertinoButton(
                      padding: EdgeInsets.zero,
                      onPressed: () => Navigator.pop(context),
                      child: const Text(
                        "取消",
                        style: TextStyle(color: ThemeVars.colorTextSec),
                      ),
                    ),
                    const Text(
                      "选择房客类型",
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    CupertinoButton(
                      padding: EdgeInsets.zero,
                      onPressed: () {
                        setState(() {
                          String selectedValue = renterTypeOptions[selectedIndex]["value"]!;
                          if (isMainRenter) {
                            _mainRenter["renterType"] = selectedValue;
                          } else if (cotenantIndex != null) {
                            _cotenantList[cotenantIndex]["renterType"] = selectedValue;
                          }
                        });
                        Navigator.pop(context);
                      },
                      child: const Text(
                        "确定",
                        style: TextStyle(color: ThemeVars.colorPrimary),
                      ),
                    ),
                  ],
                ),
              ),
              // Picker区域
              Expanded(
                child: CupertinoPicker(
                  itemExtent: 44,
                  scrollController: FixedExtentScrollController(initialItem: selectedIndex),
                  onSelectedItemChanged: (int index) {
                    selectedIndex = index;
                  },
                  children: renterTypeOptions.map((option) {
                                         return Center(
                       child: Text(
                         option["label"]!,
                         style: const TextStyle(
                           fontSize: 18,
                           color: ThemeVars.colorTextSec,
                         ),
                       ),
                     );
                  }).toList(),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
  
  // 添加同住人
  void _addCotenant() {
    Map<String, dynamic> newCotenant = {
      "name": "",
      "idCardNumber": "",
      "contacts": "",
      "picUrl": "",
      "renterType": "", // 房客类型：1为省内，2为省外
      "mainFlag": "2" // 2:同住人
    };
    
    setState(() {
      _cotenantList.add(newCotenant);
    });
  }
  
  // 删除同住人
  void _deleteCotenant(int index) {
    taiDialog(
      context: context,
      title: "提示",
      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      child: const Text("确定要删除该同住人吗？"),
      onCancel: (taiContext) {
        Stacker.pop();
      },
      onConfirm: (taiContext) {
        setState(() {
          _cotenantList.removeAt(index);
          Navigator.pop(context);
        });
      },
    );
  }

  // 渲染承租人信息
  Widget _renderMainRenterInfo() {
    return MenuBlock(
      title: const Text("承租人信息", style: TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.bold,
      )),
      borderRadius: BorderRadius.circular(8),
      items: [
        MenuBlockItem(
          text: "房客类型",
          prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError)),
          suffix: Text(
            _mainRenter["renterType"] == "1" 
                ? "省内" 
                : _mainRenter["renterType"] == "2" 
                    ? "省外" 
                    : "请选择",
            style: TextStyle(
              color: _mainRenter["renterType"].toString().isEmpty 
                  ? ThemeVars.colorTextTer 
                  : ThemeVars.colorTextSec,
            ),
          ),
          onTap: () => _showRenterTypeSelectionBottomSheet(true),
        ),
        MenuBlockItem(
          text: "姓名",
          showArrow: false,
          prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError)),
          suffix: TextFormField(
            controller: _nameController,
            textAlign: TextAlign.right,
            decoration: const InputDecoration(
              hintText: "请输入",
              border: InputBorder.none,
              isDense: true,
            ),
          ),
        ),
        MenuBlockItem(
          text: "联系方式",
          showArrow: false,
          prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError)),
          suffix: TextFormField(
            controller: _contactsController,
            textAlign: TextAlign.right,
            keyboardType: TextInputType.phone,
            decoration: const InputDecoration(
              hintText: "请输入",
              border: InputBorder.none,
              isDense: true,
            ),
          ),
        ),
        MenuBlockItem(
          text: "证件号",
          showArrow: false,
          suffix: TextFormField(
            controller: _idCardController,
            textAlign: TextAlign.right,
            keyboardType: TextInputType.text,
            decoration: const InputDecoration(
              hintText: "请输入",
              border: InputBorder.none,
              isDense: true,
            ),
          ),
          tip: const Text("证件号仅用于租客办理入住登记使用", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12)),
        ),
        MenuBlockItem(
          text: "人脸",
          onTap: () => _showImageSourceOptions(true),
          tip: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _renderFace(_mainRenter["picUrl"]),
              const SizedBox(height: 4),
              const Text("人脸仅用于租客门禁开锁使用", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12)),
            ],
          ),
        ),
      ],
    );
  }

  // 渲染同住人信息
  Widget _renderCotenantInfo(int index) {
    Map<String, dynamic> cotenant = _cotenantList[index];
    
    return MenuBlock(
      title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text("同住人 ${index + 1}", style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          )),
          GestureDetector(
            onTap: () => _deleteCotenant(index),
            child: const Text("删除", style: TextStyle(
              color: ThemeVars.colorError,
              fontSize: 14,
            )),
          ),
        ],
      ),
      borderRadius: BorderRadius.circular(8),
      items: [
        MenuBlockItem(
          text: "房客类型",
          prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError)),
          suffix: Text(
            cotenant["renterType"] == "1" 
                ? "省内" 
                : cotenant["renterType"] == "2" 
                    ? "省外" 
                    : "请选择",
            style: TextStyle(
              color: cotenant["renterType"].toString().isEmpty 
                  ? ThemeVars.colorTextTer 
                  : ThemeVars.colorTextSec,
            ),
          ),
          onTap: () => _showRenterTypeSelectionBottomSheet(false, index),
        ),
        MenuBlockItem(
          text: "姓名",
          showArrow: false,
          prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError)),
          suffix: TextFormField(
            textAlign: TextAlign.right,
            initialValue: cotenant["name"],
            decoration: const InputDecoration(
              hintText: "请输入",
              border: InputBorder.none,
              isDense: true,
            ),
            onChanged: (value) {
              setState(() {
                cotenant["name"] = value;
              });
            },
          ),
        ),
        MenuBlockItem(
          text: "联系方式",
          showArrow: false,
          prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError)),
          suffix: TextFormField(
            textAlign: TextAlign.right,
            initialValue: cotenant["contacts"],
            keyboardType: TextInputType.phone,
            decoration: const InputDecoration(
              hintText: "请输入",
              border: InputBorder.none,
              isDense: true,
            ),
            onChanged: (value) {
              setState(() {
                cotenant["contacts"] = value;
              });
            },
          ),
        ),
        MenuBlockItem(
          text: "证件号",
          showArrow: false,
          suffix: TextFormField(
            textAlign: TextAlign.right,
            initialValue: cotenant["idCardNumber"],
            keyboardType: TextInputType.text,
            decoration: const InputDecoration(
              hintText: "请输入",
              border: InputBorder.none,
              isDense: true,
            ),
            onChanged: (value) {
              setState(() {
                cotenant["idCardNumber"] = value;
              });
            },
          ),
          tip: const Text("证件号仅用于租客办理入住登记使用", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12)),
        ),
        MenuBlockItem(
          text: "人脸",
          onTap: () => _showImageSourceOptions(false, index),
          tip: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _renderFace(cotenant["picUrl"]),
              const SizedBox(height: 4),
              const Text("人脸仅用于租客门禁开锁使用", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12)),
            ],
          ),
        ),
      ],
    );
  }

  // 渲染其他信息
  Widget _renderOtherInfo() {
    return MenuBlock(
      title: const Text("其他信息", style: TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.bold,
      )),
      borderRadius: BorderRadius.circular(8),
      items: [
        MenuBlockItem(
          text: "入住房间",
          prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError)),
          suffix: Text(
            _selectedRoomName.isEmpty && _selectedBuildingName.isEmpty 
                ? "请选择房间" 
                : "$_selectedBuildingName $_selectedRoomName"
          ),
          onTap: () {
            _getEmptyRoomList().then((_) {
              _showRoomSelectionBottomSheet();
            });
          },
        ),
      ],
    );
  }
  
  @override
  void initState() {
    super.initState();
    _imagePicker = ImagePicker();
    if (isEdit) {
      _getPreCheckInDetail();
    }
  }
  
  @override
  void dispose() {
    _nameController.dispose();
    _idCardController.dispose();
    _contactsController.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: isEdit ? "编辑预登记" : "新增预登记",
      child: Stack(
        children: [
          SingleChildScrollView(
            padding: const EdgeInsets.all(ThemeVars.paddingPage),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [

                // 其他信息
                _renderOtherInfo(),
                const SizedBox(height: 16),
                // 承租人信息
                _renderMainRenterInfo(),
                
                const SizedBox(height: 16),
                
                // 同住人信息
                Column(
                  children: [
                    // 同住人列表
                    ..._cotenantList.asMap().entries.map((entry) => 
                      Padding(
                        padding: const EdgeInsets.only(bottom: 16),
                        child: _renderCotenantInfo(entry.key),
                      )
                    ),

                    // 添加同住人按钮
                    Button(
                      type: ButtonType.primaryOutline,
                      onPressed: _addCotenant,
                      child: const Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.add, size: 16),
                          SizedBox(width: 4),
                          Text("添加同住人"),
                        ],
                      ),
                    ),
                  ],
                ),
                
                // 底部按钮的空白占位
                const SizedBox(height: 80),
              ],
            ),
          ),
          
          // 底部保存按钮
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              padding: const EdgeInsets.all(ThemeVars.paddingPage),
              decoration: const BoxDecoration(
                boxShadow: [
                  BoxShadow(
                    color: ThemeVars.colorShadow,
                    blurRadius: 8,
                    offset: Offset(0, -2),
                  ),
                ],
              ),
              child: Button(
                type: ButtonType.primary,
                size: ButtonSize.large,
                onPressed: _savePreCheckIn,
                child: Text(isEdit ? "保存修改" : "提交预登记"),
              ),
            ),
          ),
        ],
      ),
    );
  }
} 